package com.yami.shop.otherservice;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yami.shop.bean.dto.UserJsonDto;
import com.yami.shop.bean.enums.UserFundDetailEnum;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 一级分销功能
 */
@Slf4j
@Service
public class OneLevelDistributionService {
    @Autowired
    private OrderService orderService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserService userService;

    @Autowired
    private UserFundDetailService userFundDetailService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderRefundService orderRefundService;

    @Autowired
    private OneLevelDistributionGrantService oneLevelDistributionGrantService;

    private static String dayBonusUserRedisPrefix="dayBonusUser:";

    /**
     * 发放每天分红
     * @param date
     */
    @Transactional
    public void grantDayBonus(String date){
        log.info("每天分红开始...");
        OneLevelDistributionGrant teamLeaderReward = oneLevelDistributionGrantService.lambdaQuery()
                .eq(OneLevelDistributionGrant::getType, "dayBonus")
                .apply("DATE_FORMAT(date, '%Y-%m-%d') = '" + date + "'").one();
        if(teamLeaderReward != null){
            return;//该天已经分过红
        }


        List<User> dayBonusUserFromRedis = getDayBonusUserFromRedis(date);
        if(dayBonusUserFromRedis == null){
            dayBonusUserFromRedis = getDayBonusUser();
        }

        String dayBonus = getValueByConfig("day_bonus");
        if(StringUtils.isBlank(dayBonus) || new BigDecimal(dayBonus).compareTo(BigDecimal.ZERO) <= 0){
            return;
        }

        DateTime parse = DateUtil.parse(date, "yyyy-MM-dd");

        //当日收货量
        Long dayBonusTakeDelivery = getDayBonusTakeDelivery(parse);
        //总分红金额
        BigDecimal multiply = new BigDecimal(String.valueOf(dayBonusTakeDelivery)).multiply(new BigDecimal(dayBonus));

        //每人可分红金额
        BigDecimal bigDecimal = multiply.divide(new BigDecimal(String.valueOf(dayBonusUserFromRedis.size()))).setScale(4, RoundingMode.DOWN);

        for(User user1:dayBonusUserFromRedis){
            User one = userService.getById(user1.getUserId());
            BigDecimal distributionBonus = one.getDistributionBonus();

            if( distributionBonus == null){
                distributionBonus = BigDecimal.ZERO;
            }

            BigDecimal add = distributionBonus.add(bigDecimal);

            User user = new User();
            user.setUserId(one.getUserId());
            user.setDistributionBonus(add);
            userService.updateById(user);

            UserFundDetail detail=new UserFundDetail();
            detail.setUserType("tz_user");
            detail.setUid(one.getUserId());
            detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
            detail.setType(UserFundDetailEnum.TYPE_9.getValue());
            detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
            detail.setMoney(bigDecimal);
            detail.setResidueMoney(add);
            detail.setTitle("每天分红");
            detail.setDetails("每天分红:"+bigDecimal +", 剩余:"+add);
            detail.setOrderNumber(null);
            detail.setDelFlag(0);

            //detail.setCreateBy(userId);
            detail.setCreateTime(new Date());
            userFundDetailService.save(detail);
        }

        //int i = 1 / 0;

        List<String> collect = dayBonusUserFromRedis.stream().map(u -> u.getUserId()).collect(Collectors.toList());

        Gson gson=new Gson();

        OneLevelDistributionGrant oneLevelDistributionGrant=new OneLevelDistributionGrant();
        oneLevelDistributionGrant.setType("dayBonus");
        oneLevelDistributionGrant.setDate(parse);
        oneLevelDistributionGrant.setUserIds(StringUtils.join(collect,","));
        oneLevelDistributionGrant.setUserJson(gson.toJson(dayBonusUserFromRedis));
        oneLevelDistributionGrant.setOrderNumber(null);
        oneLevelDistributionGrant.setOrderId(null);
        oneLevelDistributionGrant.setMoney(bigDecimal);
        oneLevelDistributionGrant.setTotalMoney(multiply);

        oneLevelDistributionGrant.setCreateTime(new Date());
        oneLevelDistributionGrant.setDelFlag(0);

        oneLevelDistributionGrantService.save(oneLevelDistributionGrant);
        log.info("每天分红结束");
    }

    /**
     * 每天的最后一秒,保存当天的可分红会员信息
     */
    public void saveDayBonusUserToRedis(){
        List<User> dayBonusUser = getDayBonusUser();

        Date date = new Date();
        String format = DateUtil.format(date, "yyyy-MM-dd");

        Gson gson=new Gson();

        //保存一天
        RedisUtil.set(dayBonusUserRedisPrefix+format,gson.toJson(dayBonusUser),86400L);
    }

    /**
     * 从redis中获取指定日期的可分红会员列表
     * @param date
     * @return
     */
    public List<User> getDayBonusUserFromRedis(String date){
        String o = (String)RedisUtil.get(dayBonusUserRedisPrefix + date);
        Gson gson=new Gson();
        Type listType = new TypeToken<List<User>>() {}.getType();
        List<User> o1 = gson.fromJson(o, listType);
        return o1;
    }

    /**
     * 获取可分红用户
     * @return
     */
    public List<User> getDayBonusUser(){
        List<User> list = userService.lambdaQuery()
                .select(User::getUserId,User::getNickName,User::getRealName)
                .in(User::getUserLevel, Arrays.asList(0, 1))
                .gt(User::getUserLevelExpireDate, new Date()).list();
        return list;
    }

    /**
     * 指定日期下单量
     * @param date
     * @return
     */
    public Long getDayBonusPlaceOrder(Date date){
        DateTime begin = DateUtil.beginOfDay(date);
        DateTime end = DateUtil.endOfDay(date);
        List<Order> list = orderService.lambdaQuery().select(Order::getOrderNumber)
                .between(Order::getPayTime,begin,end)//指定时间段确认收货的订单
                .eq(Order::getIsPayed,1)//已支付
                .in(Order::getStatus,Arrays.asList(2,3,4))//下单成功
                .list();

        List<String> collect = list.stream().map(o -> o.getOrderNumber()).collect(Collectors.toList());

        //下单数量
        Long orderQuantity=0L;

        String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
        List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));

        for(String orderNumber:collect){
            List<OrderItem> list1 = orderItemService.lambdaQuery()
                    .select(OrderItem::getOrderItemId,OrderItem::getProdCount)
                    .eq(OrderItem::getOrderNumber, orderNumber)
                    .in(OrderItem::getProdId, prodIds).list();
            //共下单了几个
            int sum1 = list1.stream().mapToInt(i -> i.getProdCount()).sum();
            for(OrderItem item:list1){
                List<OrderRefund> list2 = orderRefundService.lambdaQuery()
                        .select(OrderRefund::getGoodsNum)
                        .eq(OrderRefund::getOrderItemId, item.getOrderItemId())
                        .eq(OrderRefund::getReturnMoneySts, 1)//退款成功的
                        .list();

                //本个子订单共退款成功了几单
                int sum = list2.stream().mapToInt(r -> r.getGoodsNum()).sum();

                //本次订单还剩几单没有被退款
                int i = sum1 - sum;
                orderQuantity = orderQuantity +  i;
            }
        }

        return orderQuantity;
    }

    /**
     * 获取指定日期的收货箱数
     * @param date
     * @return
     */
    public Long getDayBonusTakeDelivery(Date date){
        DateTime begin = DateUtil.beginOfDay(date);
        DateTime end = DateUtil.endOfDay(date);
        List<Order> list = orderService.lambdaQuery().select(Order::getOrderNumber)
                .between(Order::getFinallyTime,begin,end)//指定时间段确认收货的订单
                .eq(Order::getIsPayed,1)//已支付
                .eq(Order::getStatus,5)//收货成功
                .list();

        List<String> collect = list.stream().map(o -> o.getOrderNumber()).collect(Collectors.toList());

        //下单数量
        Long orderQuantity=0L;

        String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
        List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));

        for(String orderNumber:collect){
            List<OrderItem> list1 = orderItemService.lambdaQuery()
                    .select(OrderItem::getOrderItemId,OrderItem::getProdCount)
                    .eq(OrderItem::getOrderNumber, orderNumber)
                    .in(OrderItem::getProdId, prodIds).list();
            //共下单了几个
            int sum1 = list1.stream().mapToInt(i -> i.getProdCount()).sum();
            for(OrderItem item:list1){
                List<OrderRefund> list2 = orderRefundService.lambdaQuery()
                        .select(OrderRefund::getGoodsNum)
                        .eq(OrderRefund::getOrderItemId, item.getOrderItemId())
                        .eq(OrderRefund::getReturnMoneySts, 1)//退款成功的
                        .list();

                //本个子订单共退款成功了几单
                int sum = list2.stream().mapToInt(r -> r.getGoodsNum()).sum();

                //本次订单还剩几单没有被退款
                int i = sum1 - sum;
                orderQuantity = orderQuantity +  i;
            }
        }

        return orderQuantity;
    }

    /**
     * 自动下发所有团长奖励
     * @param date
     */
    @Transactional
    public void grantTeamLeaderReward(Date date){
        log.info("团长分红开始...");
        //1.拿到所有团长
        List<User> list = userService.lambdaQuery().eq(User::getUserLevel, 1)
                .gt(User::getUserLevelExpireDate, new Date()).list();
        //2.拿到昨天收货单数,乘以奖励金额,下发奖励
        String format = DateUtil.format(date, "yyyy-MM-dd");

        for(User user:list){
            OneLevelDistributionGrant teamLeaderReward = oneLevelDistributionGrantService.lambdaQuery()
                    .eq(OneLevelDistributionGrant::getType, "teamLeaderReward")
                    .eq(OneLevelDistributionGrant::getUserIds, user.getUserId())
                    .apply("DATE_FORMAT(date, '%Y-%m-%d') = '" + format + "'").one();
            if(teamLeaderReward != null){
                continue;//该团长该日期已经发过奖励
            }
            //该团长该日期团队收货数量
            Long teamPerformance = getTeamPerformance(user.getUserId(), date);

            String teamLeaderRewardMoney = getValueByConfig("team_leader_reward");
            if(StringUtils.isBlank(teamLeaderRewardMoney) || new BigDecimal(teamLeaderRewardMoney).compareTo(BigDecimal.ZERO) <= 0){
                return;
            }
            BigDecimal distributionBonus = user.getDistributionBonus();

            if( distributionBonus == null){
                distributionBonus = BigDecimal.ZERO;
            }
            //份数与每份金额相乘
            BigDecimal multiply = new BigDecimal(teamLeaderRewardMoney).multiply(new BigDecimal(String.valueOf(teamPerformance)));
            BigDecimal add = distributionBonus.add(multiply);

            User user1 = new User();
            user1.setUserId(user.getUserId());
            user1.setDistributionBonus(add);
            userService.updateById(user1);

            UserFundDetail detail=new UserFundDetail();
            detail.setUserType("tz_user");
            detail.setUid(user.getUserId());
            detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
            detail.setType(UserFundDetailEnum.TYPE_8.getValue());
            detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
            detail.setMoney(multiply);
            detail.setResidueMoney(add);
            detail.setTitle("团队长奖励");
            detail.setDetails("团队长奖励:"+multiply +", 剩余:"+add);
            detail.setOrderNumber(null);
            detail.setDelFlag(0);

            //detail.setCreateBy(userId);
            detail.setCreateTime(new Date());
            userFundDetailService.save(detail);

            /**
             * 保存发放记录
             */
            Gson gson=new Gson();

            UserJsonDto dto=new UserJsonDto();
            dto.setUserId(user.getUserId());
            dto.setNickName(user.getNickName());
            dto.setRealName(user.getRealName());

            List<UserJsonDto> list1=new ArrayList<>();
            list1.add(dto);

            OneLevelDistributionGrant oneLevelDistributionGrant=new OneLevelDistributionGrant();
            oneLevelDistributionGrant.setType("teamLeaderReward");
            oneLevelDistributionGrant.setDate(date);
            oneLevelDistributionGrant.setUserIds(user.getUserId());
            oneLevelDistributionGrant.setUserJson(gson.toJson(list1));
            oneLevelDistributionGrant.setOrderNumber(null);
            oneLevelDistributionGrant.setOrderId(null);
            oneLevelDistributionGrant.setMoney(new BigDecimal(teamLeaderRewardMoney));
            oneLevelDistributionGrant.setTotalMoney(multiply);

            oneLevelDistributionGrant.setCreateTime(new Date());
            oneLevelDistributionGrant.setDelFlag(0);

            oneLevelDistributionGrantService.save(oneLevelDistributionGrant);
        }
        log.info("团长分红结束");
    }

    /**
     * 获取团队指定日期的收货份数
     * @param teamLeaderId
     * @param date
     * @return
     */
    public Long getTeamPerformance(String teamLeaderId,Date date){
        if(StringUtils.isBlank(teamLeaderId) || date == null){
            return null;
        }
        User byId = userService.getById(teamLeaderId);
        if(byId.getUserLevel() == null || byId.getUserLevel() != 1){
            return null;//参数用户不是团队长
        }

        //获取自己以下所有用户
        List<User>  list0=userService.getLowerLevelBySharedUid(byId.getUserId(),new ArrayList<>());
        list0.add(byId);//加上自己
        List<String> collect1 = list0.stream().map(u -> u.getUserId()).collect(Collectors.toList());


        DateTime begin = DateUtil.beginOfDay(date);
        DateTime end = DateUtil.endOfDay(date);

        List<Order> list = orderService.lambdaQuery().select(Order::getOrderNumber)
                .in(Order::getUserId, collect1)
                .between(Order::getFinallyTime,begin,end)//指定时间段确认收货的订单
                .eq(Order::getIsPayed,1)//已支付
                .eq(Order::getStatus,5)//收货成功
                .list();

        List<String> collect = list.stream().map(o -> o.getOrderNumber()).collect(Collectors.toList());

        //下单数量
        Long orderQuantity=0L;

        String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
        List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));

        for(String orderNumber:collect){
            List<OrderItem> list1 = orderItemService.lambdaQuery()
                    .select(OrderItem::getOrderItemId,OrderItem::getProdCount)
                    .eq(OrderItem::getOrderNumber, orderNumber)
                    .in(OrderItem::getProdId, prodIds).list();
            //共下单了几个
            int sum1 = list1.stream().mapToInt(i -> i.getProdCount()).sum();
            for(OrderItem item:list1){
                List<OrderRefund> list2 = orderRefundService.lambdaQuery()
                        .select(OrderRefund::getGoodsNum)
                        .eq(OrderRefund::getOrderItemId, item.getOrderItemId())
                        .eq(OrderRefund::getReturnMoneySts, 1)//退款成功的
                        .list();

                //本个子订单共退款成功了几单
                int sum = list2.stream().mapToInt(r -> r.getGoodsNum()).sum();

                //本次订单还剩几单没有被退款
                int i = sum1 - sum;
                orderQuantity = orderQuantity +  i;
            }
        }

        return orderQuantity;
    }

    /**
     * 用户第一次下单,奖励给推荐人,之后再次下单,给自己
     * @param uid
     */
    public void referenceOrderAndRepeatOrderReward(String uid,String orderNumber) {
        Order one2 = orderService.lambdaQuery().eq(Order::getOrderNumber, orderNumber).one();
        if(one2 == null){
            return;
        }
        if(one2.getStatus() != 5){
            return;
        }

        if(one2.getPlatformDeductionAmount() != null && one2.getPlatformDeductionAmount() > 0D){
            //使用了平台抵扣,不在发放奖励
            return;
        }

        Integer userProdOrderQuantity = getUserProdOrderQuantity(uid);

        //查看此订单买了几箱
        Integer productNumber = getOrderProductNumber(orderNumber);

        if(userProdOrderQuantity == 1){
            User one1 = userService.lambdaQuery().eq(User::getUserId, uid).one();
            if(one1 == null){
                return;
            }
            //奖金给一级分销的推荐人
            User one = userService.lambdaQuery().eq(User::getUserId, one1.getSharedUid()).one();
            if(one != null){
                String reward2YuanMoney = getValueByConfig("recommend_first_order");
                if(StringUtils.isBlank(reward2YuanMoney) || new BigDecimal(reward2YuanMoney).compareTo(BigDecimal.ZERO) <= 0){
                    return;
                }
                BigDecimal distributionBonus = one.getDistributionBonus();

                if( distributionBonus == null){
                    distributionBonus = BigDecimal.ZERO;
                }

                //奖励总金额
                BigDecimal multiply = new BigDecimal(reward2YuanMoney).multiply(new BigDecimal(String.valueOf(productNumber)));

                BigDecimal add = distributionBonus.add(multiply);

                User user = new User();
                user.setUserId(one.getUserId());
                user.setDistributionBonus(add);
                userService.updateById(user);

                UserFundDetail detail=new UserFundDetail();
                detail.setUserType("tz_user");
                detail.setUid(one.getUserId());
                detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                detail.setType(UserFundDetailEnum.TYPE_6.getValue());
                detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                detail.setMoney(multiply);
                detail.setResidueMoney(add);
                detail.setTitle("推荐新用户首次下单奖");
                detail.setDetails("推荐新用户首次下单奖:"+multiply +", 剩余:"+add);
                detail.setOrderNumber(orderNumber);
                detail.setDelFlag(0);

                //detail.setCreateBy(userId);
                detail.setCreateTime(new Date());
                userFundDetailService.save(detail);

                /**
                 * 保存发放记录
                 */
                Gson gson=new Gson();

                UserJsonDto dto=new UserJsonDto();
                dto.setUserId(one.getUserId());
                dto.setNickName(one.getNickName());
                dto.setRealName(one.getRealName());

                List<UserJsonDto> list=new ArrayList<>();
                list.add(dto);

                OneLevelDistributionGrant oneLevelDistributionGrant=new OneLevelDistributionGrant();
                oneLevelDistributionGrant.setType("recommendFirstOrder");
                oneLevelDistributionGrant.setDate(new Date());
                oneLevelDistributionGrant.setUserIds(one.getUserId());
                oneLevelDistributionGrant.setUserJson(gson.toJson(list));
                oneLevelDistributionGrant.setOrderNumber(one2.getOrderNumber());
                oneLevelDistributionGrant.setOrderId(one2.getOrderId());
                oneLevelDistributionGrant.setMoney(multiply);
                oneLevelDistributionGrant.setTotalMoney(multiply);

                oneLevelDistributionGrant.setCreateTime(new Date());
                oneLevelDistributionGrant.setDelFlag(0);

                oneLevelDistributionGrantService.save(oneLevelDistributionGrant);
            }
        }else{
            //奖金给自己
            User one = userService.lambdaQuery().eq(User::getUserId, uid).one();
            if(one != null){
                String reward2YuanMoney = getValueByConfig("membe_repeat_order");
                if(StringUtils.isBlank(reward2YuanMoney) || new BigDecimal(reward2YuanMoney).compareTo(BigDecimal.ZERO) <= 0){
                    return;
                }
                BigDecimal distributionBonus = one.getDistributionBonus();

                if( distributionBonus == null){
                    distributionBonus = BigDecimal.ZERO;
                }

                BigDecimal multiply = new BigDecimal(reward2YuanMoney).multiply(new BigDecimal(String.valueOf(productNumber)));

                BigDecimal add = distributionBonus.add(multiply);

                User user = new User();
                user.setUserId(one.getUserId());
                user.setDistributionBonus(add);
                userService.updateById(user);

                UserFundDetail detail=new UserFundDetail();
                detail.setUserType("tz_user");
                detail.setUid(one.getUserId());
                detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                detail.setType(UserFundDetailEnum.TYPE_7.getValue());
                detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                detail.setMoney(multiply);
                detail.setResidueMoney(add);
                detail.setTitle("会员重复下单奖");
                detail.setDetails("会员重复下单奖:"+multiply +", 剩余:"+add);
                detail.setOrderNumber(orderNumber);
                detail.setDelFlag(0);

                //detail.setCreateBy(userId);
                detail.setCreateTime(new Date());

                userFundDetailService.save(detail);

                /**
                 * 保存发放记录
                 */
                Gson gson=new Gson();

                UserJsonDto dto=new UserJsonDto();
                dto.setUserId(one.getUserId());
                dto.setNickName(one.getNickName());
                dto.setRealName(one.getRealName());

                List<UserJsonDto> list=new ArrayList<>();
                list.add(dto);

                OneLevelDistributionGrant oneLevelDistributionGrant=new OneLevelDistributionGrant();
                oneLevelDistributionGrant.setType("memberRepeatOrder");
                oneLevelDistributionGrant.setDate(new Date());
                oneLevelDistributionGrant.setUserIds(one.getUserId());
                oneLevelDistributionGrant.setUserJson(gson.toJson(list));
                oneLevelDistributionGrant.setOrderNumber(one2.getOrderNumber());
                oneLevelDistributionGrant.setOrderId(one2.getOrderId());
                oneLevelDistributionGrant.setMoney(multiply);
                oneLevelDistributionGrant.setTotalMoney(multiply);

                oneLevelDistributionGrant.setCreateTime(new Date());
                oneLevelDistributionGrant.setDelFlag(0);

                oneLevelDistributionGrantService.save(oneLevelDistributionGrant);
            }
        }
    }

    /**
     * 确认收货时,查询订单中有几个包含奖励商品的箱数
     * @param orderNumber
     * @return
     */
    public Integer getOrderProductNumber(String orderNumber) {
        String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
        List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));

        List<OrderItem> list1 = orderItemService.lambdaQuery()
                .select(OrderItem::getOrderItemId,OrderItem::getProdCount)
                .eq(OrderItem::getOrderNumber, orderNumber)
                .in(OrderItem::getProdId, prodIds).list();

        int sum1 = list1.stream().mapToInt(i -> i.getProdCount()).sum();
        return sum1;
    }

    /**
     * 获取配置项
     * @param key
     * @return
     */
    public String  getValueByConfig(String key) {
        List<String> param_value = jdbcTemplate.query("select param_value from tz_sys_config where param_key = ? ", new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("param_value");
            }
        }, key);

        if(param_value.isEmpty()){
            return null;
        }else{
            return param_value.get(0);
        }
    }

    /**
     * 获取指定用户的下单数量
     * @param uid
     * @return
     */
    public Integer getUserProdOrderQuantity(String uid) {
        String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
        List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));
        List<Order> list = orderService.lambdaQuery().select(Order::getOrderNumber).eq(Order::getUserId, uid)
                .eq(Order::getIsPayed,1)//已支付
                .in(Order::getStatus,Arrays.asList(2,3,4,5))//下单成功
                .list();

        List<String> collect = list.stream().map(o -> o.getOrderNumber()).collect(Collectors.toList());

        //下单数量
        Integer orderQuantity=0;

        for(String orderNumber:collect){
            List<OrderItem> list1 = orderItemService.lambdaQuery()
                    .select(OrderItem::getOrderItemId,OrderItem::getProdCount)
                    .eq(OrderItem::getOrderNumber, orderNumber)
                    .in(OrderItem::getProdId, prodIds).list();
            //共下单了几个
            int sum1 = list1.stream().mapToInt(i -> i.getProdCount()).sum();
            for(OrderItem item:list1){
                List<OrderRefund> list2 = orderRefundService.lambdaQuery()
                        .select(OrderRefund::getGoodsNum)
                        .eq(OrderRefund::getOrderItemId, item.getOrderItemId())
                        .eq(OrderRefund::getReturnMoneySts, 1)//退款成功的
                        .list();

                //本个子订单共退款成功了几单
                int sum = list2.stream().mapToInt(r -> r.getGoodsNum()).sum();

                //本次订单还剩几单没有被退款
                int i = sum1 - sum;
                orderQuantity = orderQuantity +  i;
            }
        }

        return orderQuantity;
    }


}
